﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WxPayAPI;
using Yule8xCommon.Applib;
using Yule8xCommon.Db;
using Yule8xModel;
using Yule8xCommon.Typelib;
using Yule8xWechat.Applib;

namespace Yule8xWechat.Payment.WxPay
{
    public partial class BuyCard : System.Web.UI.Page
    {
        protected DataTable dtGames;
        protected WxUserInfoResult wxUser;
        protected string appid;
        private string wxJsApiParam;
        protected int discount; // 优惠折扣
        protected bool isAgent;
        protected int user_id;
        protected int game_mact_id, game_id;
        protected void Page_Load(object sender, EventArgs e)
        {
            AppInfo.IsDebugMode = RuntimeDataUtil.CheckDebugModel();
            AppInfo.ForbidUpdateGameMode = RuntimeDataUtil.CheckForbidUpdateGameDb();

            user_id = RequestUtil.GetInteger("user_id");
            if (AppInfo.IsDebugMode && user_id > 0)
            {
                wxUser = UserModels.GetWxUserInfo(user_id);
                if (null == wxUser)
                {
                    ResponseUtil.WriteEnd("user_id无效!");
                }
            }
            else
            {
                wxUser = LoginPageBase.GetLoginInfo();
                if (null == wxUser)
                {
                    Response.Redirect(WechatUrls.GetUserInfoUrl("buycard"), true);
                }
            }
            /*
            // 判断登录
            object loginData = Session["login"];
            if (null != loginData)
            {
                wxUser = loginData as WxUserInfoResult;
            }
            if (null == loginData || null == wxUser)
            {
                LogUtil.Instance.WriteInfo("[购买钻石]未登录");
                Response.Redirect(WechatUrls.GetUserInfoUrl("buycard"), true);
            }
            */
            game_mact_id = RequestUtil.ParamsInteger("game_mact_id", 1);
            game_id = RequestUtil.ParamsInteger("game_id");

            // 强制要有gameid
            if (game_mact_id == 1)
            {
                if (wxUser.game_id_bozhong < 1)
                {
                    // 获取并同步gameid
                    string error;
                    wxUser.game_id_bozhong = UserModels.GetGameID(wxUser.user_id, null, "bozhong", out error);
                    if (wxUser.game_id_bozhong < 1)
                    {
                        Response.Redirect("../../Download/" + Applib.AppConf.DownloadUrl, true);
                    }
                    else
                    {
                        Session["login"] = wxUser; // 重新保存带有gameid的会话消息
                    }
                }
            }
            if (game_mact_id == 2)
            {
                if (wxUser.game_id_wanghu < 1)
                {
                    // 获取并同步gameid
                    string error;
                    wxUser.game_id_wanghu = UserModels.GetGameID(wxUser.user_id, null, "wanghu", out error);
                    if (wxUser.game_id_wanghu < 1)
                    {
                        Response.Redirect("../../Download/" + Applib.AppConf.DownloadUrl, true);
                    }
                    else
                    {
                        Session["login"] = wxUser; // 重新保存带有gameid的会话消息
                    }
                }
            }

            // 是否代理
            isAgent = UserModels.CheckUserIsAgent(wxUser.user_id);

            // 获取游戏厂商信息
            string sqlstmt = string.Format("select id, mact_code, game_name, icon_url, default_currency_name, is_enable from t_game_manufacturer where is_display=1 order by sort");
            dtGames = DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteDataTable(sqlstmt);

            discount = Applib.AppConf.CardDiscount; // 折扣
            string action = RequestUtil.FormString("action");
            if ("submit" == action)
            {
                this.DoSubmit();
            }
        }
        protected void DoSubmit()
        {
            // 买卡，普通玩家直接到游戏服务器，代理要到代理数据库，因为代理要卖卡的；为他人充值只能冲玩家ID,因为代理没必要帮人买卡
            //LogUtil.Instance.SetOutputHandler((string msg, Exception ex) => { Response.Write(msg + "<hr />"); });
            //int moneyvalueid = RequestUtil.FormInteger("moneyvalueid");
            int game_id = RequestUtil.FormInteger("game_id");
            int number = RequestUtil.FormInteger("number");
            decimal amount = RequestUtil.FormDecimal("amount");
            string payfor = RequestUtil.FormString("payfor");
            int game_mact_id = RequestUtil.FormInteger("game_mact_id");
            string pay_method = RequestUtil.FormString("pay_method");
            int parent1_uid = RequestUtil.FormInteger("parent1_uid");
            if (parent1_uid < 1)
            {
                parent1_uid = wxUser.parent1_uid;
            }
            else
            {
                // 更新用户资料
                string outmsg;
                if (!UserModels.UpdateUserParent1Info(wxUser.user_id, parent1_uid, out outmsg))
                {
                    RedirectUtil.RedirectTimer(false, "更新用户资料出错", new string[] { outmsg+", 请联系您的代理或通过公众号咨询客服!" });
                }
            }
            if (parent1_uid < 1)
            {
                RedirectUtil.RedirectTimer(false, "表单错误", new string[] { "上级用户必需填写，请联系您的代理或通过公众号咨询客服!" });
            }
            int uid = wxUser.user_id;
            string unionid = wxUser.unionid;
            //string game_nickname = string.Empty; // 从数据库获取
            string sqlstmt = string.Empty;
            LogUtil.Instance.WriteInfo(string.Format("[购买钻石] BuyCard.aspx 表单参数：game_id={0}, number={1}, amount={2}, payfor={3}", game_id, number, amount, payfor));

            if (amount < 1 || number < 1)
            {
                RedirectUtil.RedirectTimer(true, "出错啦", new string[] { "金额或数量有误!" });
                return;
            }
            bool checkGameId = true; // 是否需要检测GameID
            // 只有为自己充值，且用户是代理的情况，才无需gameid，否则都是直接充值到游戏服务器，需要检验gameid
            if ("payforme" == payfor)
            {
                if (UserModels.CheckUserIsAgent(uid))
                {
                    //game_nickname = wxUser.nickname;
                    checkGameId = false; // 用户是代理直接充值到代理钻石，无需校验gameid
                }
            }
            int game_currency_number = 0;
            switch (game_mact_id)
            {
                case 1:
                    game_currency_number = number * AppConf.GameCurrencyRate_Bozhong;
                    break;
                case 2:
                    game_currency_number = number * AppConf.GameCurrencyRate_Wanghu;
                    break;
            }
            // 判断gameid是否有效
            if (checkGameId)
            {
                if ("payforme" == payfor && game_id < 1)
                {
                    switch (game_mact_id)
                    {
                        case 1:
                            game_id = wxUser.game_id_bozhong;
                            break;
                        case 2:
                            game_id = wxUser.game_id_wanghu;
                            break;
                    }
                    if (game_id < 1)
                    {
                        RedirectUtil.RedirectTimer(true, "出错啦", new string[] { "游戏ID无效!" });
                        return;
                    }
                }
                // 获取游戏厂商信息
                DataRow rGame = dtGames.Select("id=" + game_mact_id).FirstOrDefault();
                if (null == rGame)
                {
                    RedirectUtil.RedirectTimer(true, "出错啦", new string[] { "游戏厂商不存在!" });
                    return;
                }
                switch (game_mact_id)
                {
                    case 1:
                        // 如果moneyvalue数量不存在，则先往库里面写入一条记录
                        BozhongGameUtil.CheckMoneyValue(number, amount);
                        // 查询游戏库的用户昵称
                        //game_nickname = BozhongGameUtil.GetNickName(game_id);
                        break;
                    case 2:
                        // 如果moneyvalue数量不存在，则先往库里面写入一条记录
                        WanghuGameUtil.CheckMoneyValue(game_currency_number);
                        // 查询游戏库的用户昵称
                        //game_nickname = WanghuGameUtil.GetNickName(game_id);
                        break;
                }
                if (game_mact_id == 1 && !BozhongGameUtil.CheckGameId(game_id))
                {
                    RedirectUtil.RedirectTimer(true, "出错啦", new string[] { "泊众游戏ID不存在!" });
                    return;
                }
                if (game_mact_id == 2 && !WanghuGameUtil.CheckGameId(game_id))
                {
                    RedirectUtil.RedirectTimer(true, "出错啦", new string[] { "网狐游戏ID不存在!" });
                    return;
                }
            }


            // 微信支付
            //ResponseUtil.AjaxWrite("{'info':{'openid':'" + wxUser.openid + "';total_fee:1},'status':true}".Replace("'", "\""));
            // Response.Redirect("../Payment/WxPay/AgentRegistPayForm.aspx");
            BuyDiamondAttachData attachdata = new BuyDiamondAttachData()
            {
                uid = uid,
                pfor = payfor,
                amo = amount,
                num = number,
                gmid = game_mact_id,
                guid = game_id,
                //gnn = game_nickname,
                gnum = game_currency_number
            };
            string attach = JSON.stringify(attachdata);
            LogUtil.Instance.WriteInfo(string.Format("[购买钻石] BuyCard.aspx attach={0}", attach));
            string outTradeNo = WxPayApi.GenerateOutTradeNo();
            string remark = string.Empty;
            attach = "buydiamond:" + attach; // 传递到回调函数

            // 写入充值申请表
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("out_trade_no", outTradeNo);
            data.Add("amount", amount.ToString());
            data.Add("pay_channel", pay_method);
            data.Add("user_id", uid.ToString());
            data.Add("status", "0");
            data.Add("paramstr", attach);
            sqlstmt = DbFactory.GetInsertStatement("t_finance_recharge", data);
            DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteNonQuery(sqlstmt);

            if ("trade.bankpay.native" == pay_method)
            {
                // 数据请求字符串
                string querystr = JSON.stringify(attachdata);
                // 16位数据签名
                string sign = MD5Util.GetShortMD5(AppInfo.EncryptKey + querystr);
                string url = string.Format("PayTransfer.aspx?tradeno={0}&query={1}&sign={2}", outTradeNo, Server.UrlEncode(querystr), sign);
                Response.Redirect(url, true);
            }

            // 微信支付弹窗调用
            WxJsPay(outTradeNo, amount, attach, "购买钻石");
            Response.End();

        }
        // 微信公众号支付
        void WxJsPay(string outTradeNo, decimal amount, string attach, string product_name)
        {
            string openid = wxUser.openid;
            bool onecentpay = RuntimeDataUtil.CheckOnecentPay(wxUser.user_id); // 一分钱支付
            string total_fee = onecentpay ? "1" : (amount * 100).ToString(); // 分
            if (onecentpay)
            {
                LogUtil.Instance.WriteError(string.Format("[购买钻石] BuyCard.aspx user_id={0}, total_fee={1}, amount={2} 使用OCP支付模式", wxUser.user_id, total_fee, amount), null);
            }

            //若传递了相关参数，则调统一下单接口，获得后续相关接口的入口参数
            JsApiPay jsApiPay = new JsApiPay(this);
            jsApiPay.openid = openid;
            jsApiPay.total_fee = (int)decimal.Parse(total_fee);

            //JSAPI支付预处理
            try
            {
                WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(outTradeNo, attach, product_name);
                wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数

                LogUtil.Instance.WriteInfo("[购买钻石] BuyCard.aspx wxJsApiParam: " + wxJsApiParam);
                LogUtil.Instance.WriteInfo("[购买钻石] BuyCard.aspx 订单详情: " + unifiedOrderResult.ToPrintStr());

                string str = "<script>function jsApiCall() { WeixinJSBridge.invoke( 'getBrandWCPayRequest'," + wxJsApiParam + ", function (res) { WeixinJSBridge.log(res.err_msg); if(res.err_msg=='get_brand_wcpay_request:ok'){window.location.replace('../../Agent/Index.aspx');} } ); } function callpay() { if (typeof WeixinJSBridge == \"undefined\") { if (document.addEventListener) { document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); } else if (document.attachEvent) { document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } } else { jsApiCall(); } } callpay();</script>";
                LogUtil.Instance.WriteInfo("[购买钻石] BuyCard.aspx 发起微信支付脚本：" + str);
                Response.Write(str);
            }
            catch (Exception ex)
            {
                LogUtil.Instance.WriteInfo("[购买钻石] BuyCard.aspx 下单失败，请返回重试" + ex.Message);
                RedirectUtil.RedirectTimer(true, "出错啦", new string[] { "下单失败，请返回重试" });
            }
        }
    }
}